package com.eco.utils;

import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class GenerateToken {

	@Autowired
	Cache<String,Object> caffeineCache;

	/**
	 * 生成令牌
	 * 
	 * @param keyPrefix
	 *            令牌key前缀
	 * @param cacheValue
	 *            Cache存放的值
	 * @return 返回token
	 */
	public String createToken(String keyPrefix, String cacheValue) {
		if (StringUtils.isEmpty(cacheValue)) {
			log.error("cacheValue is NULL");
		}
		String token = keyPrefix + UUID.randomUUID().toString().replace("-", "");
		caffeineCache.put(token,cacheValue);
		return token;
	}

	/**
	 * 根据token获取Cache中的value值
	 * 
	 * @param token
	 * @return
	 */
	public String getToken(String token) {
		if (StringUtils.isEmpty(token)) {
			log.error("token is NULL");
			return null;
		}
		String value = (String) caffeineCache.getIfPresent(token);
		return value;
	}

	/**
	 * 移除token
	 * 
	 * @param token
	 * @return
	 */
	public void removeToken(String token) {
		if (StringUtils.isEmpty(token)) {
			log.error("token is NULL");
			return;
		}
		caffeineCache.asMap().remove(token);
	}

}
